// 封装server
var config = require('./config')
var http = require("http")
var url = require('url')
var mime = require('mime')
var path = require("path")
var fs = require('fs')
var ejs = require('ejs')
var zlib = require('zlib')
var os = require('os')
var childProcess = require('child_process')


var template = fs.readFileSync(path.join(__dirname, "index.html"), "utf8")
function Server() {
  this.config= config  // 配置
  this.template = template // 模板
}
// 获取ip
Server.prototype.getIp = function() {
  var ip = ''
  var localObj = os.networkInterfaces()
  for(var item in localObj) {
    localObj[item].forEach(function(items) {
      if(items.family === 'IPv4' && items.internal === false) {
        ip= items.address
      }
    })
  }
  return ip
}
// 打开默认浏览器
Server.prototype.openBrowser = function(url) {
  var cmd = ''
  if(process.platform === 'win32') {
    cmd = 'start "%ProgramFiles%\Internet Explorer\iexplore.exe"'
  } else if (process.platform === 'linux') {
    cmd = 'xdg-open'
  } else if (process.platform === 'darwin') {
    cmd = 'open'
  }
  childProcess.exec(`${cmd} ${url}`)
}
// 启动方法
Server.prototype.start = function() {
  // 通过http 创建服务器
  var that = this
  var httpserver = http.createServer(function(request,response) {
    that.pathname = url.parse(request.url, true).pathname;
    that.pathurl = path.join(config.dir,url.parse(request.url, true).pathname)
    // 检查文件是否存在
    fs.stat(that.pathurl,(err, stats) => {
      if (err) {
        that.sendError(request, response,err)
      } else {
        if(stats.isFile()) {
          that.sendFile(request, response, stats)
        } else {
          //去找寻文件夹文件
          that.sendFolder(request, response, stats)
        } 
      }  
    })
  })
  // 配置端口
  var {port,host} = config
  httpserver.listen(port!==0 ? port : 0)
  httpserver.on('listening', function() { 
    var port = httpserver.address().port
    that.openBrowser(`http://${that.getIp()}:${port}`)
    console.log(`server start http://${that.getIp()}:${port}`)
    console.log(`server start http://${host}:${port}`)
  })
}
// 添加缓存
Server.prototype.cache = function(request, response, statObj) {
  // 设置强缓存
  response.setHeader('Cache-Control','no-cache')
  response.setHeader("Expires", new Date(Date.now() + 30 * 1000).toUTCString())
  
  // 设置对比缓存
  // 上次修改时间
  var etag = statObj.ctime.toGMTString() + statObj.size
  var lastModified = statObj.ctime.toGMTString()
  response.setHeader('Etag',etag)
  response.setHeader('Last-Modified',lastModified)

  // 客户端得到得时间
  // 客户端把上次设置修改时间带过来
  var ifNoneMatch = request.headers['if-none-match']
  var ifModifiedSince = request.headers['if-modified-since']
  if (etag !== ifNoneMatch && lastModified !== ifModifiedSince) {
    return false
  } else {
    return true
  }
}
// 压缩文件
Server.prototype.gzip = function(request, response, statObj) {
  response.setHeader("Content-Encoding", "gzip")
  return zlib.createGzip() //创建一个转换流
}
// 判断文件是否存在
Server.prototype.sendError = function(request, response,err) {
  response.writeHead(404)
  response.end("没有这个路径")
}
// 找寻文件夹的文件
Server.prototype.sendFolder = function(request, response, statObj) {
  // 读取当前的文件夹
  var that = this
  fs.readdir(that.pathurl,(err, file)=> {
    var dirs = file.map(dir => ({ 
      name: dir, 
      path: path.join(that.pathname, dir)
    }))
    // ejs渲染
    var pageData = ejs.render(that.template, { dirs })
    response.setHeader("Content-Type", "text/html;charset=utf8")
    response.end(pageData)
  })
}
// 读取文件
Server.prototype.sendFile = function(request, response, statObj) {
  // 读取当前的文件
  var that = this
  // 如果缓存
  if(that.cache(request, response, statObj)) {
    response.writeHead(304)
    response.end()
  } else {
    const readStream = fs.createReadStream(that.pathurl)
    response.setHeader("Content-Type", `${mime.getType(that.pathurl)};charset=utf8`)
    var gzip = that.gzip(request, response, statObj)
    if(gzip) {
      return readStream.pipe(gzip).pipe(response)
    }
    readStream.pipe(response)
  }
  
}
// var server= new Server()
// server.start()
module.exports = Server